<template>
  <view class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="编辑招聘信息" :showBack="true"/>

    <view class="daily-recruitment">
      <view class="post-form">
        <!-- 基本信息 -->
        <view class="form-group">
          <text class="label">职位标题</text>
          <input
              type="text"
              v-model="formData.positionName"
              class="input"
              placeholder="请输入职位标题"
          />
          <text v-if="formErrors.positionName" class="error-text">{{ formErrors.positionName }}</text>
        </view>

        <view class="form-group">
          <text class="label">职位类型</text>
          <view
              class="picker-input"
              :class="{ 'error-border': formErrors.type }"
              @click="showTypePicker = true"
          >
            <text class="picker-text">{{ jobTypeText || '请选择职位类型' }}</text>
          </view>
          <text v-if="formErrors.type" class="error-text">{{ formErrors.type }}</text>
        </view>

        <view class="form-group">
          <text class="label">公司名称</text>
          <input
              type="text"
              v-model="formData.corporateName"
              class="input"
              placeholder="请输入公司名称"
          />
          <text v-if="formErrors.corporateName" class="error-text">{{ formErrors.corporateName }}</text>
        </view>

        <view class="form-group">
          <text class="label">工作地点</text>
          <input
              type="text"
              v-model="formData.location"
              class="input"
              placeholder="请输入工作地点"
          />
          <text v-if="formErrors.location" class="error-text">{{ formErrors.location }}</text>
        </view>

        <!-- 职位要求 -->
        <view class="form-group">
          <text class="label">经验要求</text>
          <view
              class="picker-input"
              :class="{ 'error-border': formErrors.experience }"
              @click="showExperiencePicker = true"
          >
            <text class="picker-text">{{ formData.experience || '请选择经验要求' }}</text>
          </view>
          <text v-if="formErrors.experience" class="error-text">{{ formErrors.experience }}</text>
        </view>

        <view class="form-group">
          <text class="label">薪资</text>
          <view class="flex items-center">
            <input
              type="number"
              v-model="formData.salary"
              class="input flex-1"
              :disabled="formData.pay_status == 1"
              placeholder="请输入薪资（如：200元/天）"
            />
            <text class="ml-[24rpx] text-[32rpx] text-blue-600">元/天</text>
          </view>
          <text v-if="formErrors.salary" class="error-text">{{ formErrors.salary }}</text>
        </view>

        <view class="form-group">
          <text class="label">工作时间</text>
          <input
              type="text"
              v-model="formData.timeFrame"
              class="input"
              placeholder="请输入工作时间"
          />
          <text v-if="formErrors.timeFrame" class="error-text">{{ formErrors.timeFrame }}</text>
        </view>

        <view class="form-group">
          <text class="label">招聘人数</text>
          <input
              type="text"
              v-model="formData.number"
              class="input"
              :disabled="formData.pay_status == 1"
              placeholder="请输入招聘人数"
          />
          <text v-if="formErrors.number" class="error-text">{{ formErrors.number }}</text>
        </view>

        <!-- 职位描述 -->
        <view class="form-group">
          <text class="label">详细描述</text>
          <nut-textarea
              v-model="formData.description"
              class="textarea"
              placeholder="请输入详细描述"
          />
          <text v-if="formErrors.description" class="error-text">{{ formErrors.description }}</text>
        </view>

        <!-- 适合人群 -->
        <view class="form-group">
          <text class="label">适合人群</text>
          <view class="flex flex-wrap gap-2">
            <view 
              v-for="item in suitablePersons" 
              :key="item.id"
              class="px-3 py-1 rounded-full border transition-all duration-200"
              :class="[
                selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600',
                formData.pay_status != 1 ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'
              ]"
              @click="selectGroup(item.id)"
            >
              <text class="text-[22rpx]">{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 截止日期 -->
        <view class="form-group">
          <text class="label">招聘截止</text>
          <view
              class="picker-input"
              :class="{ 'error-border': formErrors.deadline }"
              @click="showDeadlinePicker = true"
          >
            <text class="picker-text">{{ formData.deadline || '请选择截止日期' }}</text>
          </view>
          <text v-if="formErrors.deadline" class="error-text">{{ formErrors.deadline }}</text>
        </view>

        <!-- 状态更改 -->
        <!-- <view class="form-group">
          <text class="label">招聘状态</text>
          <view
              class="picker-input"
              :class="{ 'error-border': formErrors.status }"
              @click="showStatusPicker = true"
          >
            <text class="picker-text">{{ statusText || '请选择招聘状态' }}</text>
          </view>
          <text v-if="formErrors.status" class="error-text">{{ formErrors.status }}</text>
        </view> -->


        <!-- 提交按钮 -->
        <nut-button class="submit-btn" @click="handleSubmit">保存编辑</nut-button>
      </view>

      <!-- 选择器弹窗 -->
      <nut-popup v-model:visible="showTypePicker" position="bottom" round>
        <nut-picker
            v-model="jobTypesValue"
            :columns="jobTypes"
            title="选择职位类型"
            @confirm="onTypeConfirm"
            @cancel="showTypePicker = false"
        />
      </nut-popup>

      <nut-popup v-model:visible="showExperiencePicker" position="bottom" round>
        <nut-picker
            :columns="experienceOptions.map(exp => ({ text: exp, value: exp }))"
            title="选择经验要求"
            @confirm="onExperienceConfirm"
            @cancel="showExperiencePicker = false"
        />
      </nut-popup>

      <nut-popup v-model:visible="showDeadlinePicker" position="bottom" round>
        <nut-date-picker
            title="选择截止日期"
            @confirm="onDeadlineConfirm"
            @cancel="showDeadlinePicker = false"
        />
      </nut-popup>

      <nut-popup v-model:visible="showStatusPicker" position="bottom" round>
        <nut-picker
            :columns="statusOptions.map(exp => ({text: exp, value: exp}))"
            title="选择岗位状态"
            @confirm="onStatusConfirm"
            @cancel="showStatusPicker = false"
        />
      </nut-popup>

    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue'
import Taro from '@tarojs/taro'
import {post} from "@/utils/request";
// import {Textarea as nutTextarea} from '@nutui/nutui-taro';
// import {Popup as nutPopup} from '@nutui/nutui-taro';
// import {Picker as nutPicker} from '@nutui/nutui-taro';
// import {DatePicker as nutDatePicker} from '@nutui/nutui-taro';
// import {Button as nutButton} from '@nutui/nutui-taro';
import {getCurrentInstance} from "@tarojs/runtime";
import PageHeader from "@/components/PageHeader.vue";

/** 表单数据类型 */
interface JobFormData {
  id: string
  positionName: string
  type: string
  corporateName: string
  location: string
  experience: string
  salary: string
  timeFrame: string
  description: string
  number: string
  deadline: string
  update_time:string
  status:number
}

/**定义获取职位类型接口*/
interface JobTypeColumn {
  update_time: number,
  create_time: number,
  name: string,
  id: number,
  pic: string
}

interface JobTypeItem {
  columns: JobTypeColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

const jobTypeText = ref()
const jobTypesValue = ref<string[]>([])
/** 职位类型选项 */
const jobTypes = ref([
  {
    text: '',
    value: ''
  }
  //'普工', '技工', '管理', '质检', '仓储', '后勤', '其他'
])

/** 经验要求选项 */
const experienceOptions = [
  '不限', '1年以下', '1-3年', '3-5年', '5年以上'
]


const statusOptions = [
  '招聘中', '停止招聘'
]

// 适合人群相关
const suitablePersons = ref<any[]>([]);
const selectedGroupId = ref<number>(0); // 默认为"不限"

/**获取职位类型*/
getType()
function getType() {
  post('/dictionary/recruitmentDailyLabel').then(res => {
    jobTypes.value = res.data.map((item: JobTypeItem) => ({
      text: item.columns.name,
      value: item.columns.id.toString()
    }));
  })
}

/**
 * 获取适合人群列表
 */
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 0, name: "不限" },
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

/**
 * 选择适合人群
 * @param groupId 人群ID
 */
const selectGroup = (groupId: number) => {
  if (formData.pay_status == 1) return; // 如果已支付不可编辑，直接返回
  
  selectedGroupId.value = groupId;
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

/** 表单数据 */
const formData = reactive<JobFormData>({
  id: '',
  positionName: '',
  type: '',
  corporateName: '',
  location: '',
  experience: '',
  salary: '',
  timeFrame: '',
  description: '',
  number: '',
  deadline: '',
  update_time:'',
  status: 0
})

/** 表单验证状态 */
const formErrors = reactive<Partial<JobFormData>>({})

/** 选择器显示状态 */
const showTypePicker = ref(false)
const showExperiencePicker = ref(false)
const showDeadlinePicker = ref(false)
const showStatusPicker = ref(false)
//招聘状态值
const statusText = ref("")
//职位类型默认值
const pickerTitle = ref("")

//当前id对应的数据
const currentInfo = ref<any>({})

//获取路由参数的‘id’
const courseId = getCurrentInstance()
const id = courseId.router?.params.id as string || ""
formData.id = id
console.log("id",id)

/** 表单验证 */
function validateForm(): boolean {
  const errors: Partial<JobFormData> = {}

  if (!formData.positionName.trim()) errors.positionName = '请输入职位标题'
  if (!formData.type) errors.type = '职位类请选择型'
  if (!formData.corporateName.trim()) errors.corporateName = '请输入公司名称'
  if (!formData.location.trim()) errors.location = '请输入工作地点'
  if (!formData.experience) errors.experience = '请选择经验要求'
  if (!formData.salary.trim()) errors.salary = '请输入薪资'
  if (!formData.timeFrame.trim()) errors.timeFrame = '请输入工作时间'
  if (!formData.description.trim()) errors.description = '请输入职位描述'
  if ( Number(formData.number)<1) errors.number = '请输入招聘人数'
  if (!formData.deadline) errors.deadline = '请选择截止日期'

  Object.assign(formErrors, errors)
  return Object.keys(errors).length === 0
}

/** 提交表单 */
function handleSubmit() {

  // 生成当前时间，格式：YYYY - MM - DD HH:mm:ss
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  formData.update_time = formattedTime

  console.log("formData", formData);
  if (!validateForm()) {
    Taro.showToast({title: '请完善必填信息', icon: 'none', duration: 2000})
    return
  }

  Taro.showLoading({title: '发布中...'})

  setTimeout(() => {
    Taro.hideLoading()
    const jobFormData: any = {
      ...formData,
      groupTypes: selectedGroupId.value || 0 // 添加适合人群参数
    }
    console.log("参数列表", jobFormData)
    post('/recruitmentDaily/save', jobFormData)
        .then(res => {
          if (res.code === 0) {
            Taro.showToast({title: '编辑成功！', icon: 'success', duration: 2000})
            Taro.redirectTo({
              url:'/pages/post/my-publish'
            })
          } else {
            Taro.showToast({title: '编辑失败！', icon: 'error', duration: 2000})
          }
        })
  }, 1500)
}

/** 选择器确认事件 */
function onTypeConfirm(value: any) {
  if (value.selectedValue && value.selectedValue.length > 0) {
    jobTypesValue.value = value.selectedValue
    //jobTypes.value = categoryOptions.value.find(item => item.value === String(val.selectedValue[0]))?.text
    jobTypeText.value = jobTypes.value.find(item => item.value === String(value.selectedValue[0]))?.text
  }
  formData.type = String(value?.selectedValue[0] || '')
  showTypePicker.value = false
}

function onExperienceConfirm(value: any) {
  formData.experience = value?.selectedValue[0] || ''
  showExperiencePicker.value = false
}


//进行状态的更改
function onStatusConfirm(value: any) {
  console.log("选项",value.selectedValue[0])
  if(value?.selectedValue[0] === "招聘中"){
    //console.log("进入")
    statusText.value = "招聘中"
    formData.status = 0
  }
  else {
    statusText.value = "停止招聘"
    formData.status = 1
  }
  showStatusPicker.value = false
}

function onDeadlineConfirm(value: any) {
  const [year, month, day] = value.selectedValue || []
  formData.deadline = year && month && day ? `${year}-${month}-${day}` : ''
  showDeadlinePicker.value = false
}

//通过id获取当前修改的订单数据
const detail = async ()=>{
  const res = await post("/recruitmentDaily/getById", {id: formData.id});
  if(res.code == "0"){
    currentInfo.value = res.data.columns
    console.log("current当前数据",currentInfo.value)
    
    // 将获取到的详情数据直接赋值给表单字段
    formData.positionName = currentInfo.value.position_name || ''
    formData.corporateName = currentInfo.value.corporate_name || ''
    formData.location = currentInfo.value.location || ''
    formData.salary = currentInfo.value.salary || ''
    formData.timeFrame = currentInfo.value.time_frame || ''
    formData.number = currentInfo.value.number || ''
    formData.description = currentInfo.value.description || ''
    formData.type = currentInfo.value.type || ''
    formData.pay_status = currentInfo.value.pay_status || ''
    //将获取到的类型值转换为文本值并在页面显示
    jobTypeText.value = jobTypes.value.find((item) => item.value === String(currentInfo.value.type))?.text
    //将获取到的经验要求显示到页面上
    formData.experience = experienceOptions.find((exp) => exp ===currentInfo.value.experience)
    //将获取到的截止时间显示到页面上
    formData.deadline = currentInfo.value.deadline
    // 设置适合人群
    selectedGroupId.value = currentInfo.value.groupTypes || 0;
    //console.log("进入666666666",jobTypeText.value)
    // if(currentInfo.value.status === 1){
    //   //console.log("进入666666666")
    //   statusText.value = "招聘中"
    //   formData.status = 1
    // }
    // else {
    //   //console.log("没进入66666666")
    //   statusText.value = "停止招聘"
    //   formData.status = 2
    // }
  }
}

// 初始化数据
getSuitablePersons();
detail();
</script>

<style>
/* 基础容器样式 */
.daily-recruitment {
  background-color: #f5f5f5;
}

/* 表单容器样式 */
.post-form {
  background-color: white;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 表单组样式 */
.form-group {
  margin-bottom: 30rpx;
}

/* 标签样式 */
.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

/* 输入框样式 */
.input, .textarea, .picker-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: white;
}

/* 选择器输入框样式 */
.picker-input {
  display: flex;
  align-items: center;
  min-height: 76rpx;
  cursor: pointer;
}

.picker-text {
  color: #333;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picker-input placeholder {
  color: #999;
}

/* 文本域样式 */
.textarea {
  min-height: 180rpx;
  resize: vertical;
}

/* 错误提示样式 */
.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
}

.error-border {
  border-color: #f44336 !important;
}

/* 提交按钮样式 */
.submit-btn {
  background-color: #1976d2 !important;
  color: white !important;
  width: 100%;
  margin-top: 40rpx;
  padding: 24rpx 40rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

/* 输入框聚焦样式 */
input:focus, textarea:focus, .picker-input:focus {
  outline: none;
  border-color: #1976d2;
}
.nut-textarea{
  padding: 0 !important;
}
</style>